// 自动导入组件的通用工具方法
import {defineAsyncComponent} from "vue";
import {filter_object} from "@/js/s94_tool.js";

const import_function_map = import.meta.glob(`./*/*.vue`);

const import_function_group_map = {}
Object.keys(import_function_map).forEach(path=>{
    let path_info = path.split('/');
    let name = path_info.pop().replace('.vue', '');
    if (name.indexOf('_') === 0) return;
    let dir = path_info.pop();
    import_function_group_map[dir] = import_function_group_map[dir] || {}
    import_function_group_map[dir][name] = import_function_map[path];
})

console.log(import_function_group_map, '自动导入的组件')

/**
 * 返回异步组件枚举，用于门户组件批量引入组件使用
 * @param {string} dir 需要导入的 vue 组件存放目录
 * @returns {{}}
 */
export function defineAsyncComponentMap(dir){
    let function_map = import_function_group_map[dir] || {};
    let res = {}
    Object.keys(function_map).forEach(name => {
        res[name] = defineAsyncComponent(function_map[name]);
    })
    return res;
}

/**
 * 获取组件枚举
 * @param {string} dir 需要导入的 vue 组件存放目录
 * @returns { Promise<{[componentName:string]: Object}> }
 */
export function componentMap(dir){
    let function_map = import_function_group_map[dir] || {};
    return Promise.all(Object.values(function_map).map(func=>func())).then(component_list=>{
        let name_list = Object.keys(function_map);
        let res = {}
        component_list.forEach((row,i)=>{
            let name = name_list[i];
            res[name] = row.default;
        })
        return res;
    })
}

function filterKey(obj, exclude=[]){
    obj = filter_object(obj, exclude, [/^_.+_$/]);
    let res = {}
    Object.keys(obj).forEach(k=>{
        let key = k.substring(1, k.length-1);
        res[key] = obj[k];
    });
    return res;
}

export async function componentConfigMap(dir){
    let map = await componentMap(dir);
    let config = {};
    Object.keys(map).forEach(k=>{
        let row = map[k];
        let prop_map = {};
        const props = row.props || {};
        Object.keys(props).forEach(k2=>{
            let prop = props[k2];
            prop_map[k2] = Object.assign(filterKey(prop, ['_label_', '_default_', '_tip_', '_input_type_']), {
                name: k2,
                label: prop._label_ || '',
                tip: prop._tip_ || '',
                input_type: prop._input_type_ || '',
                is_required: !!prop.required,
                is_boolean: prop.type === Boolean,
                default: prop._default_ || prop.default,
            })
        })
        config[k] = Object.assign(filterKey(row, ['_title_', '_tip_', '_css_var_', '_head_img_', '_group_']), {
            name: k,
            title: row._title_ || '',
            tip: row._tip_ || '',
            _css_var_: row._css_var_ || {},
            _head_img_: row._head_img_ || '',
            _group_: row._group_ || '',
            prop_map: prop_map,
        })
    })
    return config;
}